<?php

namespace Platform\Controller;

use Think\Controller;

class BaseController extends Controller {

	public $app;

	public function _initialize() {
		$this->checkApp();
	}

	public function checkApp() {
		$app_id = I('app_id', '', 'trim');
		$app = D('Common/Platform')->getByAppId($app_id);
		if (!$app) {
			return $this->errApp();
		}
		$this->app = $app;
	}

	public function checkSign($params) {
		$sign = I('sign');
		ksort($params);
		$signStr = http_build_query($params);
		if ($sign !== md5($signStr . '&' . $this->app['app_secret'])) {
			return $this->errSign();
		}
	}

	public function response($code, $info, $data = '') {
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Headers: X-Requested-With');
		$res = compact('code', 'info', 'data');
		$this->ajaxReturn($res);
	}

	public function resErr($code, $info = '') {
		return $this->response($code, $info);
	}

	public function resOK($data) {
		return $this->response(ERR_SUCCESS, '', $data);
	}

	public function errParam() {
		return $this->resErr(ERR_PARAM, '参数错误');
	}

	public function errSign() {
		return $this->resErr(ERR_SIGN, '签名错误');
	}

	public function errApp() {
		return $this->resErr(ERR_APPID, 'AppID错误');
	}

}